<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单编号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="取餐号" prop="queueNum">
        <el-input
          v-model="queryParams.queueNum"
          placeholder="请输入取餐号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间" style="width: 308px">
        <el-date-picker
          v-model="daterangeOrderCreateTime"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-if="hasSearched" v-loading="loading" :data="ordersList" @selection-change="handleSelectionChange">
      <!-- 订单编号采用固定前缀加日期加自增序号生成 -->
      <el-table-column label="订单编号" align="center" prop="orderNo" />
      <!-- 采用日期+自增序号来生成取餐号 -->
      <el-table-column label="取餐号" align="center" prop="queueNum" />
      <!-- 备注只显示两行 -->
      <el-table-column label="备注" align="center" prop="orderDesc">
        <template #default="scope">
          <div style="display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; text-overflow: ellipsis; max-width: 100%;">
            {{ scope.row.orderDesc }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="订单总额" align="center" prop="orderPrice" />
      <el-table-column label="支付方式" align="center"
                       prop="payType" :formatter="formatPayType" />
      <el-table-column label="实付价格" align="center" prop="realPrice" />
      <!--   通过地址id获取联系人姓名、电话、配送地址（地址不展示，仅内部使用）  -->
      <el-table-column label="联系人姓名" align="center">
        <template #default="scope">
          {{ scope.row.receiverName || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="电话" align="center" width="110px">
        <template #default="scope">
          {{ scope.row.receiverTel || '-' }}
        </template>
      </el-table-column>
      <!-- 配送地址组合为 scope.row.deliveryAddress（不显示） -->
      <el-table-column label="配送地址" align="center" prop="deliveryAddress">
        <template #default="scope">
          <div style="display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; text-overflow: ellipsis; max-width: 100%;">
            {{ scope.row.deliveryAddress }}
          </div>
        </template>
      </el-table-column>
      <!-- 订单状态(1-待支付 2-待发货 3-待配送 4-配送中 5-已完成 6-已取消 7-售后处理中) -->
      <el-table-column label="订单状态" width="100px" align="center" prop="orderStatus" :formatter="formatOrderStatus"/>
      <el-table-column label="下单时间" align="center" prop="payTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.payTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="goDetail(scope.row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-empty v-else description="请输入订单信息进行搜索" />
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />


  </div>
</template>

<script setup name="TakeAfterSales">
import { listOrders, getOrders, delOrders, addOrders, updateOrders } from "@/api/order/orders"
import { listAddress, getAddress } from "@/api/order/address.js";
import { listOrderGoods } from "@/api/order/orderGoods";
import { listOrderGoodsSpec } from "@/api/order/orderGoodsSpec.js";
import { useRouter } from 'vue-router'
import {listShop} from "@/api/order/shop.js";
import {listFrontUser} from "@/api/order/frontUser.js";
import { listBusiness, getBusiness } from "@/api/order/business.js";
import useUserStore from "@/store/modules/user";

const { proxy } = getCurrentInstance()
const router = useRouter()
const userStore = useUserStore()

const ordersList = ref([])
const addressList = ref([])
const open = ref(false)
const loading = ref(false)
const hasSearched = ref(true) // 改为true，让页面默认显示数据
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const daterangePayTime = ref([])
const daterangeOrderCreateTime = ref([])
const daterangeOrderEndTime = ref([])
const daterangeOrderEstimateTime = ref([])
const daterangeOrderCompleteTime = ref([])
const daterangeTakeTime = ref([])

// 当前用户的shopId
const currentUserShopId = ref(null)



const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderNo: null,
    userId: null,
    addressId: null,
    shopId: null,
    shopAddress: null,
    isCoupons: null,
    couponsId: null,
    orderClass: null,
    orderDesc: null,
    queueNum: null,
    deliveryFees: null,
    totalWrapFees: null,
    orderPrice: null,
    realPrice: null,
    platformExtractRatio: null,
    platformExtractPrice: null,
    platformDeliveryFee: null,
    platformIncome: null,
    businessDeliveryFee: null,
    businessIncome: null,
    payType: null,
    payTime: null,
    orderCreateTime: null,
    orderEndTime: null,
    orderEstimateTime: null,
    orderCompleteTime: null,
    deliveryType: null, // 不限制配送方式，显示所有类型
    takeTime: null,
    obligatePhone: null,
    orderStatus: 7, // 固定为售后处理中的订单
    isPrinted: null,
    isPayToMerchant: null,
    isDelete: null,
    isAfterSales: null,
    isEvaluate: null
  },
  rules: {
    orderNo: [
      { required: true, message: "订单编号不能为空", trigger: "blur" }
    ],
    userId: [
      { required: true, message: "用户id，关联用户表不能为空", trigger: "blur" }
    ],
    orderPrice: [
      { required: true, message: "订单总价格不能为空", trigger: "blur" }
    ],
    realPrice: [
      { required: true, message: "实付价格不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

// 根据支付方式的值显示具体名称
function formatPayType(row) {
  const typeMap = {1: '微信支付', 2: '支付宝', 3: '其他'};
  return typeMap[row.payType] || '';
}
// 根据配送方式值显示配送方式名称
function formatDeliveryType(row) {
  const typeMap = {1: '外卖', 2: '自取'};
  return typeMap[row.deliveryType] || '';
}
// 根据订单状态值显示订单状态名称
// 订单状态(1-待支付 2-待发货 3-待配送 4-配送中 5-已完成 6-已取消 7-售后处理中)
function formatOrderStatus(row) {
  const typeMap = {1: '待支付', 2: '待发货', 3: '待配送', 4: '配送中', 5: '已完成', 6: '已取消', 7: '售后处理中'};
  return typeMap[row.orderStatus] || '';
}

// 店铺id映射名称
const shopNameMap = ref({})
// 通过店铺id显示店铺名
function displayShopName(shopId) {
  return shopNameMap.value?.[shopId] ?? shopId
}

// 获取当前登录用户的shopId
async function getCurrentUserShopId() {
  try {
    const userId = userStore.id
    console.log('当前用户ID:', userId)
    if (!userId) {
      console.error('未获取到当前用户ID')
      return
    }
    
    // 根据userId查询business信息
    const businessResponse = await listBusiness({ userId: userId })
    console.log('business查询结果:', businessResponse)
    
    if (businessResponse.rows && businessResponse.rows.length > 0) {
      const business = businessResponse.rows[0]
      currentUserShopId.value = business.shopId
      console.log('当前用户shopId:', currentUserShopId.value)
    } else {
      console.error('未找到当前用户对应的商家信息')
    }
  } catch (error) {
    console.error('获取当前用户商家信息失败:', error)
  }
}

// 载入映射数据
async function loadRefMaps() {
  try {
    const [ shopsResp ] = await Promise.all([
      listShop({ pageNum: 1, pageSize: 9999 }),
    ])
    const sMap = {}
    ;(shopsResp?.rows || []).forEach(s => {
      if (s && s.shopId != null) sMap[s.shopId] = s.shopName || s.shopId
    })
    shopNameMap.value = sMap
  } catch (e) {
    // 忽略映射加载错误，表格仍显示原ID
  }
}

/** 查询订单查询列表 */
async function getList() {
  if (!currentUserShopId.value) {
    console.error('未获取到当前用户的shopId，无法查询订单')
    return
  }
  
  loading.value = true
  queryParams.value.params = {}
  if (null != daterangePayTime && '' != daterangePayTime) {
    queryParams.value.params["beginPayTime"] = daterangePayTime.value[0]
    queryParams.value.params["endPayTime"] = daterangePayTime.value[1]
  }
  if (null != daterangeOrderCreateTime && '' != daterangeOrderCreateTime) {
    queryParams.value.params["beginOrderCreateTime"] = daterangeOrderCreateTime.value[0]
    queryParams.value.params["endOrderCreateTime"] = daterangeOrderCreateTime.value[1]
  }
  if (null != daterangeOrderEndTime && '' != daterangeOrderEndTime) {
    queryParams.value.params["beginOrderEndTime"] = daterangeOrderEndTime.value[0]
    queryParams.value.params["endOrderEndTime"] = daterangeOrderEndTime.value[1]
  }
  if (null != daterangeOrderEstimateTime && '' != daterangeOrderEstimateTime) {
    queryParams.value.params["beginOrderEstimateTime"] = daterangeOrderEstimateTime.value[0]
    queryParams.value.params["endOrderEstimateTime"] = daterangeOrderEstimateTime.value[1]
  }
  if (null != daterangeOrderCompleteTime && '' != daterangeOrderCompleteTime) {
    queryParams.value.params["beginOrderCompleteTime"] = daterangeOrderCompleteTime.value[0]
    queryParams.value.params["endOrderCompleteTime"] = daterangeOrderCompleteTime.value[1]
  }
  if (null != daterangeTakeTime && '' != daterangeTakeTime) {
    queryParams.value.params["beginTakeTime"] = daterangeTakeTime.value[0]
    queryParams.value.params["endTakeTime"] = daterangeOrderEndTime.value[1]
  }
  
  // 将shopId和订单状态作为查询参数
  queryParams.value.shopId = currentUserShopId.value
  queryParams.value.orderStatus = 7 // 售后处理中
  
  try {
    const response = await listOrders(queryParams.value)
    console.log('API返回的订单数据:', response.rows)
    console.log('当前用户shopId:', currentUserShopId.value)
    
    ordersList.value = response.rows || []
    total.value = response.total || 0
    console.log('订单数量:', response.total)
    console.log('订单数据:', response.rows)
    
    await enrichOrdersWithAddress(ordersList.value)
  } finally {
    loading.value = false
  }
}

// 基于 addressId 补充联系人姓名、电话及组合后的配送地址
async function enrichOrdersWithAddress(rows) {
  if (!Array.isArray(rows) || rows.length === 0) return
  const addressIdSet = new Set(rows.map(r => r && r.addressId).filter(id => id))
  if (addressIdSet.size === 0) return

  const cache = new Map()
  const tasks = Array.from(addressIdSet).map(id =>
    getAddress(id)
      .then(res => {
        cache.set(id, res && res.data ? res.data : null)
      })
      .catch(() => {
        cache.set(id, null)
      })
  )
  await Promise.allSettled(tasks)

  rows.forEach(row => {
    const addr = cache.get(row.addressId)
    if (addr) {
      row.receiverName = addr.receiverName || ''
      row.receiverTel = addr.receiverTel || ''
      const parts = [addr.addressProvince, addr.addressCity, addr.addressTown, addr.addressDetail]
      row.deliveryAddress = parts.filter(Boolean).join('')
    } else {
      row.receiverName = row.receiverName || ''
      row.receiverTel = row.receiverTel || ''
      row.deliveryAddress = row.deliveryAddress || ''
    }
  })
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  hasSearched.value = true
  getList()
  loadRefMaps()
}

/** 重置按钮操作 */
function resetQuery() {
  daterangePayTime.value = []
  daterangeOrderCreateTime.value = []
  daterangeOrderEndTime.value = []
  daterangeOrderEstimateTime.value = []
  daterangeOrderCompleteTime.value = []
  daterangeTakeTime.value = []
  proxy.resetForm("queryRef")
  // 重置后仍然显示数据，重新获取
  hasSearched.value = true
  getList()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.orderId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

// 跳转详情页
function goDetail(row) {
  const payload = {
    orderId: row.orderId,
    orderNo: row.orderNo,
    userId: row.userId,
    addressId: row.addressId,
    shopId: row.shopId,
    shopAddress: row.shopAddress,
    orderDesc: row.orderDesc,
    queueNum: row.queueNum,
    orderPrice: row.orderPrice,
    realPrice: row.realPrice,
    payType: row.payType,
    payTime: row.payTime,
    orderCreateTime: row.orderCreateTime,
    orderCompleteTime: row.orderCompleteTime,
    deliveryType: row.deliveryType,
    takeTime: row.takeTime,
    orderStatus: row.orderStatus,
    receiverName: row.receiverName,
    receiverTel: row.receiverTel,
    deliveryAddress: row.deliveryAddress
  }
  router.push({
    path: '/order/orders/detail',
    query: { 
      data: encodeURIComponent(JSON.stringify(payload)),
      fromTakeAfterSales: 'true' // 标识从待处理售后页面进入
    }
  })
}



// 页面初始化
onMounted(async () => {
  console.log('页面开始初始化...')
  await getCurrentUserShopId()
  console.log('获取到shopId后:', currentUserShopId.value)
  
  if (currentUserShopId.value) {
    console.log('开始加载映射数据...')
    loadRefMaps()
    console.log('开始获取订单列表...')
    // 页面加载时自动获取数据
    getList()
  } else {
    console.error('未能获取到shopId，无法加载数据')
  }
})
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>